package top.hekun.study.winlog;

import com.sun.jna.platform.win32.Advapi32Util;
import com.sun.jna.platform.win32.WinNT;

import java.sql.Timestamp;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.List;

/**
 * @Author: 贺坤
 * @Date: 2021/1/22 15:34
 */
public class WinLog {

    public static void main(String[] args) {
        // 结果集
        List<Event> eventList = new ArrayList<>();
        // 获取系统的日志记录器
        Advapi32Util.EventLogIterator iter = new Advapi32Util.EventLogIterator("EventLog");
            // 字符串缓冲器
            StringBuffer logString = new StringBuffer();
        // 循环遍历
        while (iter.hasNext()) {
            // 获取当前日志记录
            Advapi32Util.EventLogRecord eventLogRecord = iter.next();
            // 获取日志信息
            String[] str = eventLogRecord.getStrings();
            if (str != null && str.length>0) {
                for (String s : str) {
                    logString.append(s);
                }
            }
            // 获取日志记录
            WinNT.EVENTLOGRECORD record = eventLogRecord.getRecord();
            // 判读日志时候是 关机时间记录
            if ( (eventLogRecord.getStatusCode())== Type.SHUTDOWN_RECORD.getEventId()) {
                // 复合条件的 存储
                eventList.add(Event.builder()
                        .id("0X"+Integer.toHexString(eventLogRecord.getEventId()))
                        .time(new Timestamp(record.TimeGenerated.longValue() * 1000).toLocalDateTime())
                        .type(eventLogRecord.getType().toString())
                        .category(record.EventCategory.toString())
                        .source(eventLogRecord.getSource())
                        .statusCode(eventLogRecord.getStatusCode())
                        .log(logString.toString())
                        .build());
            }
            // 清空缓冲区
            logString.setLength(0);
        }
        // 排序 最近的关机记录在最前
        Collections.sort(eventList);
        // 打印结果
        eventList.forEach(System.out::println);
    }
}
